﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.good
{
    public partial class good_list : SF.Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        protected string goodTypeId;
        protected string keywords = string.Empty;
        //onSale：已上架，offSale：已下架
        protected string status;
        protected string prolistview = string.Empty;
        protected string busnieseNum = "", appNum = "", templatesNum = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            this.goodTypeId = DTRequest.GetQueryString("goodTypeId");
            this.keywords = DTRequest.GetQueryString("keywords");
            this.status = DTRequest.GetQueryString("status");
            if (String.IsNullOrWhiteSpace(status))
            {
                status = "onSale";
            }
            this.pageSize = GetPageSize(10); //每页数量
            this.prolistview = Utils.GetCookie("good_info_list_view"); //显示方式
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("good_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
                string busnieseNum = mgr.busnieseNum.ToString();
                string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
                string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();
                if (string.IsNullOrEmpty(templatesNum))
                {
                    JscriptMsg("请先在商品管理中选择模版！", "/admin/modeconfig/malltemplet_list.aspx");
                    return;
                }
                TreeBind(); //绑定类别
                //绑定列表
                RptBind(this.status, this.goodTypeId, " id>0 and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum) + CombSqlTxt(this.keywords), " sort");
            }
        }

        #region 绑定类别

        /// <summary>
        /// 绑定的是类别编号 非 自增编号
        /// </summary>
        private void TreeBind()
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            busnieseNum = mgr.busnieseNum.ToString();
            appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            BLL.bs_good_type bll = new BLL.bs_good_type();
            DataTable dt = bll.GetList(0, Utils.getWhereByInfo(busnieseNum, appNum, templatesNum), "id asc").Tables[0];
            this.ddlGoodType.Items.Clear();
            this.ddlGoodType.Items.Add(new ListItem("所有分类", ""));
            foreach (DataRow dr in dt.Rows)
            {
                string id = dr["id"].ToString();
                int classLayer = int.Parse(dr["class_layer"].ToString());
                string typeName = dr["typeName"].ToString().Trim();
                if (classLayer == 1)
                {
                    this.ddlGoodType.Items.Add(new ListItem(typeName, id));
                }
                else
                {
                    typeName = "├ " + typeName;
                    typeName = Utils.StringOfChar(classLayer - 1, "　") + typeName;
                    this.ddlGoodType.Items.Add(new ListItem(typeName, id));
                }
            }
        }
        #endregion

        #region 数据绑定
        private void RptBind(string status, string goodTypeId, string _strWhere, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            if (!String.IsNullOrEmpty(goodTypeId))
            {
                this.ddlGoodType.SelectedValue = goodTypeId;
            }
            //if (status > 0)
            //{
            ddlShelf.SelectedValue = status;
            //}
            this.txtKeywords.Text = this.keywords;
            //图表或列表显示
            BLL.bs_good_info bll = new BLL.bs_good_info();
            switch (this.prolistview)
            {
                //文字列表
                case "Txt":
                    this.rptList2.Visible = false;
                    this.rptList1.DataSource = bll.GetList(status, goodTypeId, this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    this.rptList1.DataBind();
                    break;
                //图片列表
                default:
                    this.rptList1.Visible = false;
                    this.rptList2.DataSource = bll.GetList(status, goodTypeId, this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    this.rptList2.DataBind();
                    break;
            }
            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}&page={3}", status, goodTypeId.ToString(), this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (names like '%"
                    + _keywords + "%' or brandName like '%" + _keywords + "%' or place like '%" + _keywords + "%') ");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回图文每页数量
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("good_info_page_size"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //设置操作
        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ChkAdminLevel("good_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            this.RptBind(this.status, this.goodTypeId, "  id>0" + CombSqlTxt(this.keywords), "sort asc,id desc");
        }

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}",
                this.status.ToString(), this.goodTypeId.ToString(), txtKeywords.Text));
        }

        //筛选类别
        protected void ddlGoodType_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}", ddlShelf.SelectedValue, ddlGoodType.SelectedValue, this.keywords));
        }
        //&&上架与下架处理条件筛选
        protected void ddlShelf_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}", ddlShelf.SelectedValue, ddlGoodType.SelectedValue, this.keywords));
        }

        //设置文字列表显示
        protected void lbtnViewTxt_Click(object sender, EventArgs e)
        {
            Utils.WriteCookie("good_info_list_view", "Txt", 14400);
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}&page={3}",
                this.status.ToString(), this.goodTypeId.ToString(), this.keywords, this.page.ToString()));
        }

        //设置图文列表显示
        protected void lbtnViewImg_Click(object sender, EventArgs e)
        {
            Utils.WriteCookie("good_info_list_view", "Img", 14400);
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}&page={3}",
                 this.status.ToString(), this.goodTypeId.ToString(), this.keywords, this.page.ToString()));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("good_info_page_size", _pagesize.ToString(), 43200);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}",
                 this.status.ToString(), this.goodTypeId.ToString(), this.keywords));
        }

        /// <summary>
        /// 保存排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("good_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            BLL.bs_good_info bll = new BLL.bs_good_info();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt64(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                int sortId;
                if (!int.TryParse(((TextBox)rptList.Items[i].FindControl("txtSortId")).Text.Trim(), out sortId))
                {
                    sortId = 99;
                }
                bll.UpdateField(id, "sort=" + sortId.ToString());
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "保存商品排序"); //记录日志
            JscriptMsg("保存排序成功啦！", Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}",
                 this.status.ToString(), this.goodTypeId.ToString(), this.keywords));
        }

        /// <summary>
        /// 批量上架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOnShelf_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("good_list", DTEnums.ActionEnum.OnShelf.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.bs_good_info bll = new BLL.bs_good_info();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt64(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (bll.UpdateField(id, "status='onSale'"))
                    {
                        sucCount++;
                    }
                    else
                    {
                        errorCount++;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "上架商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("上架成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}", this.status.ToString(), this.goodTypeId.ToString(), this.keywords));
        }

        /// <summary>
        /// 批量下架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOffShelf_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("good_list", DTEnums.ActionEnum.OffShelf.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.bs_good_info bll = new BLL.bs_good_info();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (bll.UpdateField(id, "status='offSale'"))
                    {
                        sucCount++;
                    }
                    else
                    {
                        errorCount++;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "下架商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("下架成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}", this.status.ToString(), this.goodTypeId.ToString(), this.keywords));
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("good_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.bs_good_info bll = new BLL.bs_good_info();
            //Model.sf_goods_info model;
            BLL.sf_goods_img bllImg = new BLL.sf_goods_img();
            //BLL.sf_goods_orderdetal detaBll = new BLL.sf_goods_orderdetal();
            Repeater rptList = new Repeater();
            switch (this.prolistview)
            {
                case "Txt":
                    rptList = this.rptList1;
                    break;
                default:
                    rptList = this.rptList2;
                    break;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    //检查是否含有订单数据（后续处理）
                    //if (detaBll.GetList("goodsNum='" + bll.GetModel(id).goodsNum + "'").Tables[0].Rows.Count <= 0)
                    //{
                    //关联的删除，也写在Delete方法里面了
                    if (bll.Delete(id))
                    {
                        sucCount++;
                    }
                    else
                    {
                        errorCount++;
                    }
                    //}
                    //else
                    //{
                    //    errorCount++;
                    //}
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除商品内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！ 含有订单数据，不能删除，可进行下架操作！", Utils.CombUrlTxt("good_list.aspx", "status={0}&goodTypeId={1}&keywords={2}", this.status.ToString(), this.goodTypeId.ToString(), this.keywords));
        }
    }
}